using Domain;
using ErrorCode;
using MediatR;
using SqlSugar;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using WriteAPI.Command.生产计划;

namespace WriteAPI.CommandHandle.生产计划
{
    /// <summary>
    /// 更新生产计划命令处理程序
    /// </summary>
    public class UpdateProductionPlanCommandHandler : IRequestHandler<UpdateProductionPlanCommand, APIResult<bool>>
    {
        private readonly ISqlSugarClient _db;

        public UpdateProductionPlanCommandHandler(ISqlSugarClient db)
        {
            _db = db;
        }

        public async Task<APIResult<bool>> Handle(UpdateProductionPlanCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<bool>
            {
                Data = false
            };

            if (request.Id <= 0)
            {
                result.Message = "计划ID无效";
                return result;
            }

            try
            {
                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    // 1. 检查主表记录是否存在
                    var plan = await _db.Queryable<Lwp_ProductionPlan>()
                        .FirstAsync(p => p.Id == request.Id);
                    
                    if (plan == null)
                    {
                        result.Message = "生产计划不存在";
                        return result;
                    }

                    // 2. 更新主表记录
                    plan.VersionDesc = request.PlanTheme;  // 计划主题
                    plan.DocNumber = request.PlanNumber;   // 计划单号
                    plan.BizNumber = request.SalesOrder;   // 销售订单号
                    plan.BizUser = request.RelatedProject; // 关联项目
                    plan.DocDate = request.DocumentDate;   // 单据日期
                    plan.Remark = request.Remarks;         // 备注

                    // 3. 处理物品明细
                    var totalQuantity = 0m;

                    // 3.1 处理需要删除的物品明细
                    if (request.DeletedItemIds != null && request.DeletedItemIds.Any())
                    {
                        await _db.Deleteable<ProductionPlanDetail>()
                            .Where(d => request.DeletedItemIds.Contains(d.Id))
                            .ExecuteCommandAsync();
                    }

                    // 3.2 处理需要更新的物品明细
                    if (request.UpdatedItems != null && request.UpdatedItems.Any())
                    {
                        foreach (var item in request.UpdatedItems)
                        {
                            var detail = await _db.Queryable<ProductionPlanDetail>()
                                .FirstAsync(d => d.Id == item.Id);

                            if (detail != null)
                            {
                                detail.ItemCode = item.ItemCode;
                                detail.ItemName = item.ItemName;
                                detail.Spec = item.Spec;
                                detail.Unit = item.Unit;
                                detail.ItemCategory = item.ItemCategory;
                                detail.ItemClass = item.ItemClass;
                                detail.Brand = item.Brand;
                                detail.Quantity = item.Quantity;
                                detail.DetailDate = item.DetailDate;
                                detail.MainUnitQuantity = item.MainUnitQuantity;
                                detail.Remark = item.Remark;
                                
                                await _db.Updateable(detail).ExecuteCommandAsync();
                                totalQuantity += item.Quantity;
                            }
                        }
                    }

                    // 3.3 处理新增的物品明细
                    if (request.NewItems != null && request.NewItems.Any())
                    {
                        var details = request.NewItems.Select(item => new ProductionPlanDetail
                        {
                            PlanId = request.Id,
                            ItemCode = item.ItemCode,
                            ItemName = item.ItemName,
                            Spec = item.Spec,
                            Unit = item.Unit,
                            ItemCategory = item.ItemCategory,
                            ItemClass = item.ItemClass,
                            Brand = item.Brand,
                            Quantity = item.Quantity,
                            DetailDate = item.DetailDate,
                            MainUnitQuantity = item.MainUnitQuantity,
                            Remark = item.Remark
                        }).ToList();
                        
                        await _db.Insertable(details).ExecuteCommandAsync();
                        totalQuantity += details.Sum(d => d.Quantity);
                    }

                    // 4. 处理附件
                    // 4.1 处理需要删除的附件
                    if (request.DeletedAttachmentIds != null && request.DeletedAttachmentIds.Any())
                    {
                        await _db.Deleteable<ProductionPlanAttachment>()
                            .Where(a => request.DeletedAttachmentIds.Contains(a.Id))
                            .ExecuteCommandAsync();
                    }

                    // 4.2 处理新增的附件
                    if (request.NewAttachments != null && request.NewAttachments.Any())
                    {
                        var attachments = request.NewAttachments.Select(attach => new ProductionPlanAttachment
                        {
                            PlanId = request.Id,
                            FileName = attach.FileName,
                            FilePath = attach.FilePath,
                            FileSize = attach.FileSize,
                            FileType = attach.FileType,
                            UploadTime = attach.UploadTime
                        }).ToList();
                        
                        await _db.Insertable(attachments).ExecuteCommandAsync();
                    }

                    // 5. 更新总数量
                    if (totalQuantity > 0)
                    {
                        // 如果已经计算了一部分的数量，再查询剩余的数量
                        var remainingItems = await _db.Queryable<ProductionPlanDetail>()
                            .Where(d => d.PlanId == request.Id)
                            .ToListAsync();
                        
                        plan.TotalQuantity = Convert.ToInt32(remainingItems.Sum(d => d.Quantity));
                    }

                    // 6. 保存主表更新
                    await _db.Updateable(plan).ExecuteCommandAsync();

                    scope.Complete();

                    result.Success = true;
                    result.Code = 200;
                    result.Message = "生产计划更新成功";
                    result.Data = true;
                }
            }
            catch (Exception ex)
            {
                result.Message = $"更新生产计划失败: {ex.Message}";
            }

            return result;
        }
    }
} 